
package hackathon.techbooster.tanabata;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
    private static final String TAG = MainActivity.class.getSimpleName();

    private ProgressDialog mProgressDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        findViewById(R.id.btn_create).setOnClickListener(this);
        findViewById(R.id.btn_list).setOnClickListener(this);

        if (!PreferenceUtils.checkFont(this)) {
            Log.d(TAG, "font url=" + getString(R.string.font_url, PreferenceUtils.FONT_NAME));
            new FontLoadAsync().execute(getString(R.string.font_url, PreferenceUtils.FONT_NAME));
        }
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.btn_create:
                intent = new Intent(MainActivity.this, CreateActivity.class);
                break;
            case R.id.btn_list:
                intent = new Intent(MainActivity.this, ShowListActivity.class);
                intent.putExtra(PreferenceUtils.KEY_TWITTER, false);
                break;

        }
        startActivity(intent);
    }

    public class FontLoadAsync extends AsyncTask<String, Void, File> {
        private final int BUFFER_SIZE = 10240;

        @Override
        protected void onPreExecute() {
            // プログレスダイアログのセットアップ
            mProgressDialog = new ProgressDialog(MainActivity.this);
            mProgressDialog.setMessage(getString(R.string.now_downloading));
            mProgressDialog.setIndeterminate(false);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setMax(1);
            mProgressDialog.show();
        }

        @Override
        protected File doInBackground(String... url) {
            File file = null;
            try {
                file = getHttpData(url[0]);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return file;
        }

        @Override
        protected void onPostExecute(File file) {
            super.onPostExecute(file);
            mProgressDialog.dismiss();

            if (file == null) {
                Toast.makeText(getApplicationContext(), R.string.error_download_font,
                        Toast.LENGTH_SHORT).show();
            }
        }

        private File getHttpData(String url) throws IOException {
            HttpClient httpClient = null;
            File fontFile = null;
            try {
                httpClient = new DefaultHttpClient();

                HttpGet request = new HttpGet(url);
                httpClient.getParams().setParameter("http.connection.timeout", new Integer(15000));
                HttpResponse httpResponse = httpClient.execute(request);
                int responseCode = httpResponse.getStatusLine().getStatusCode();

                // ファイルサイズを取得して、プログレスダイアログにセット
                mProgressDialog.setMax((int) httpResponse.getEntity().getContentLength());

                switch (responseCode) {
                    case HttpStatus.SC_OK:
                        fontFile = PreferenceUtils.getFontFile(getApplicationContext());

                        InputStream inputStream = httpResponse.getEntity().getContent();
                        BufferedInputStream bufferedInputStream = new BufferedInputStream(
                                inputStream, BUFFER_SIZE);
                        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
                                new FileOutputStream(fontFile, false), BUFFER_SIZE);

                        byte buffer[] = new byte[BUFFER_SIZE];
                        int size = 0;
                        while (-1 != (size = bufferedInputStream.read(buffer))) {
                            bufferedOutputStream.write(buffer, 0, size);
                            // onProgressUpdateを呼び出す
                            // 読み込み済み分のサイズと新たに読み込まれたサイズを足して、ダイアログに再セット
                            mProgressDialog.setProgress(mProgressDialog.getProgress() + size);
                            // publishProgress(size);
                        }

                        bufferedOutputStream.flush();

                        bufferedOutputStream.close();
                        bufferedInputStream.close();
                        break;
                    case HttpStatus.SC_NOT_FOUND:
                        Toast.makeText(getApplicationContext(), R.string.error_404,
                                Toast.LENGTH_SHORT).show();
                        Log.e(TAG, "404 not found");
                        break;
                    case HttpStatus.SC_REQUEST_TIMEOUT:
                        Toast.makeText(getApplicationContext(), R.string.error_timeout,
                                Toast.LENGTH_SHORT).show();
                        Log.e(TAG, "server timeout");
                        break;
                    default:
                        throw new IOException("status error:status=" + responseCode);
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
                Log.e(TAG, "ClientProtocolException:"+e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
                Log.e(TAG, "IOException:"+e.getMessage());
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
            return fontFile;
        }
    }

}
